import datetime
from django.http import JsonResponse

from userApp.models import *

from datetime import datetime

month_cty_list=['北京','上海','重庆','石家庄','太原','沈阳','长春','哈尔滨','南京','杭州','合肥','福州','南昌',
'济南','郑州','武汉','长沙','广州','海口','成都','贵阳','昆明','西安','兰州','西宁','台北','呼和浩特','南宁',
'拉萨','银川','乌鲁木齐']

# 获取月份列表
def getMonthDate():
    # 获取所有不重复的 weather_date
    MonthList = Part2.objects.values_list('weather_date', flat=True).distinct().order_by('weather_date')
    # distinct_dates 现在是一个包含所有不重复日期的 QuerySet
    print("获取到的月份数据：",MonthList)
    # 可以将其传递给模板或进行其他处理
    return MonthList


# 获取月平均高温、平均低温
def getAverageTemp(date):
    # 进行条件查询，筛选出符合条件的记录
    weatherListByCity = Part2.objects.filter(weather_date__startswith=date)
    xData = []  # 城市名
    y1Data = []  # 平均高温
    y2Data = []  # 平均低温

    for i in weatherListByCity:
        if i.city in month_cty_list:
            xData.append(i.city)
            y1Data.append(float(i.avg_high_temperature))
            y2Data.append(float(i.avg_low_temperature))

    print('月平均高低温数据',xData, y1Data, y2Data)
    return xData, y1Data, y2Data

# 获取月极端高温、极端低温
def getMinMaxTemp(date):
    # 进行条件查询，筛选出符合条件的记录
    weatherListByCity = Part1.objects.filter(weather_date__startswith=date)
    xCityData = []  # 城市名
    y1MaxData = []  # 极端高温
    y2MinData = []  # 极端低温

    for i in weatherListByCity:
        if i.city in month_cty_list:
            xCityData.append(i.city)
            y1MaxData.append(float(i.max_temperature))
            y2MinData.append(float(i.min_temperature))

    print(xCityData, y1MaxData, y2MinData)
    return xCityData, y1MaxData, y2MinData


# 获取月空气质量
def getMinMaxAir(date):
    # 进行条件查询，筛选出符合条件的记录
    airListByCity = Part3.objects.filter(weather_date__startswith=date)
    xCityData = []  # 城市名
    y1MaxData = []  # 空气良好
    y2MinData = []  # 空气恶劣

    for i in airListByCity:
        xCityData.append(i.city)
        y1MaxData.append(float(i.mastAir))
        y2MinData.append(float(i.lostAir))

    print(xCityData, y1MaxData, y2MinData)
    return xCityData, y1MaxData, y2MinData

# 获取平均空气质量
def get_avg_air(date):
    airListByCity = Part4.objects.filter(weather_date__startswith=date)
    xCityData = []
    yAirData=[]
    for i in airListByCity:
        xCityData.append(i.city)
        yAirData.append(float(i.averageAir))
    return xCityData, yAirData



# 获取城市列表
def get_city_List():
    cityList=WeatherInfo.objects.values_list('city', flat=True).distinct()
    print("获取到的城市列表",cityList)
    return cityList



'''城市数据年度分析'''
# 获取某城市的所有最高温度和最低温度
def get_city_temperature(date,Year):
    city_temperature = WeatherInfo.objects.filter(city__startswith=date,date__year=Year).order_by('date')  # 添加排序
    xdate=[]
    y1date=[]
    y2date=[]
    for i in city_temperature:
        xdate.append(i.date)
        y1date.append(float(i.mastHeightDay))
        y2date.append(float(i.mastSmallDay))
    return xdate, y1date, y2date

# 获取某城市的风力、风向、天气状况
def get_city_weather(date,Year):
    city_data = WeatherInfo.objects.filter(city__startswith=date,date__year=Year)
    wetaher_counts = {}
    wind_counts = {}
    level_counts = {}

    for entry in city_data:
        # 统计天气状况
        wetaher = entry.wearther
        wetaher_counts[wetaher] = wetaher_counts.get(wetaher, 0) + 1

        # 统计风向
        wind = entry.wind
        wind_counts[wind] = wind_counts.get(wind, 0) + 1

        # 统计风力等级
        level = entry.windlevel
        level_key = f"Level {level}"
        level_counts[level_key] = level_counts.get(level_key, 0) + 1

    # 格式化数据以便在饼图中使用
    wetaherList = [{'name': key, 'value': value} for key, value in wetaher_counts.items()]
    windList = [{'name': key, 'value': value} for key, value in wind_counts.items()]
    levelList = [{'name': key, 'value': value} for key, value in level_counts.items()]
    return wetaherList, windList, levelList

# 获取某城市的空气质量情况
def getCityAir(date,Year):
    # city_data =Part3.objects.filter(city__startswith=date,weather_date__year=Year)
    city_data = Part3.objects.filter(
        city__startswith=date,
        weather_date__startswith=str(Year)
    ).order_by('weather_date')
    # city_data =WeatherInfo.objects.filter(city__startswith=date).order_by('date')
    xdata=[]
    y1data=[]
    y2data=[]
    for city in city_data:
        xdata.append(city.weather_date)
        y1data.append(float(city.mastAir))
        y2data.append(float(city.lostAir))
    return xdata, y1data, y2data



'''城市数据月分析'''
# 获取城市某月的最高温度、最低温度、平均温度
def getMonthWeather(city, date_str):
    # 解析日期为月份
    try:
        month_date = datetime.strptime(date_str, "%Y-%m")
    except ValueError:
        return [], [], [], []  # 返回空数据，如果日期格式不正确

    year = month_date.year
    month = month_date.month

    # 过滤特定城市和月份的数据
    weatherData = WeatherInfo.objects.filter(
        city__startswith=city,
        date__year=year,
        date__month=month
    ).order_by('date')

    # 提取日期、最高温度、最低温度和计算平均温度
    xdata = []
    y1data = []
    y2data = []
    y3data = []  # 用于存储每日平均温度

    total_mastHeightDay = 0
    days = 0

    for day in weatherData:
        xdata.append(day.date.strftime("%Y-%m-%d"))
        y1data.append(float(day.mastHeightDay))  # 最高温度
        y2data.append(float(day.mastSmallDay))   # 最低温度

        # 计算每日平均温度（假设平均温度是 (最高温度 + 最低温度) / 2）
        average_temp = (float(day.mastHeightDay) + float(day.mastSmallDay)) / 2
        y3data.append(average_temp)  # 添加到平均温度列表

        total_mastHeightDay += float(day.mastHeightDay)
        days += 1


    return xdata, y1data, y2data, y3data

# 获取月份分析的卡片信息
def getMonthCard(city,date):
    month_date1 =Part1.objects.get(city=city,weather_date__startswith=date)
    month_date2 =Part2.objects.get(city=city,weather_date__startswith=date)
    month_date3 =Part3.objects.get(city=city,weather_date__startswith=date)
    avg_high_temperature=month_date2.avg_high_temperature
    avg_low_temperature=month_date2.avg_low_temperature
    high_temperature=month_date1.max_temperature
    print(high_temperature)
    low_temperature=month_date1.min_temperature
    high_air =month_date3.mastAir
    low_air=month_date3.lostAir
    print(avg_high_temperature,avg_low_temperature,high_temperature,low_temperature,high_air,low_air)
    return avg_high_temperature,avg_low_temperature,high_temperature,low_temperature,high_air,low_air


# 获取某城市某月的风力、风向
def getMonthWind(city, date_str):
    # 解析日期为月份
    try:
        month_date = datetime.strptime(date_str, "%Y-%m")
    except ValueError:
        return [], []

    year = month_date.year
    month = month_date.month

    # 过滤特定城市和月份的数据
    weatherData = WeatherInfo.objects.filter(
        city__startswith=city,
        date__year=year,
        date__month=month
    ).order_by('date')

    # 提取日期和风力等级
    xdata = []
    y1data = []

    for day in weatherData:
        xdata.append(day.date.strftime("%Y-%m-%d"))
        wind_level = day.windlevel

        # 检查是否为"微"
        if wind_level == "微":
            wind_level_int = 0.5
        else:
            # 去掉 '级' 字，并尝试转换为整数
            wind_level = wind_level.rstrip('级') if wind_level else '0'
            try:
                wind_level_int = int(wind_level)
            except ValueError:
                wind_level_int = 0  # 默认值

        y1data.append(wind_level_int)


    return xdata, y1data





"""天气大屏"""
"""天气大屏"""
# 轮播表数据
def getweatherInfo(selected_date):
    # 查询指定日期的天气数据
    data = WeatherInfo.objects.filter(date=selected_date)

    # 将查询结果转换为列表
    weather_data = []
    for item in data:
        weather_data.append({
            'date': item.date,
            'city': item.city,
            'weather': item.wearther,
            'level': item.windlevel
        })

    return weather_data

def getmapdata(selected_date):
    # 手动创建省份城市的列表
    province_cities = {
        '北京': '北京',
        '天津': '天津',
        '河北': '石家庄',
        '山西': '太原',
        '内蒙古': '呼和浩特',
        '辽宁': '沈阳',
        '吉林': '长春',
        '黑龙江': '哈尔滨',
        '上海': '上海',
        '江苏': '南京',
        '浙江': '杭州',
        '安徽': '合肥',
        '福建': '福州',
        '江西': '南昌',
        '山东': '济南',
        '河南': '郑州',
        '湖北': '武汉',
        '湖南': '长沙',
        '广东': '广州',
        '广西': '南宁',
        '海南': '海口',
        '重庆': '重庆',
        '四川': '成都',
        '贵州': '贵阳',
        '云南': '昆明',
        '西藏': '拉萨',
        '陕西': '西安',
        '甘肃': '兰州',
        '青海': '西宁',
        '宁夏': '银川',
        '新疆': '乌鲁木齐',
        '台湾': '台北',
        '香港': '香港',
        '澳门': '澳门',
    }

    # 获取所有省份城市
    cities = province_cities.values()

    # 查询指定日期的天气数据，只获取 province_cities 中的城市
    data = WeatherInfo.objects.filter(date=selected_date, city__in=cities)

    map_data = {}
    for item in data:
        # 假设最高温字段为 mastHeightDay
        city = item.city
        temperature = float(item.mastHeightDay) if item.mastHeightDay else 0.0
        # 找到对应的省份名
        province = None
        for key, value in province_cities.items():
            if value == city:
                province = key
                break

        if province:
            map_data[province] = temperature

    return map_data

# 统计某一天五个一线城市的最高温最低温情况
# 柱状图数据
def get_max_temp_data(selected_date):
    # 获取指定日期的一线城市最高温最低温数据
    cities = ['北京', '上海', '广州', '深圳', '成都','重庆']
    data = WeatherInfo.objects.filter(city__in=cities, date=selected_date)
    max_temp_data = []
    for city in cities:
        city_data = data.filter(city=city).first()
        if city_data:
            max_temp_data.append({
                'city': city,
                'maxtemp': float(city_data.mastHeightDay),
                'mintemp': float(city_data.mastSmallDay)
            })
        else:
            max_temp_data.append({
                'city': city,
                'maxtemp': 0.0,
                'mintemp': 0.0
            })
    return max_temp_data
# 城市统计
def get_city_count(selected_date):
    # 查询指定日期下的所有城市记录
    cities = WeatherInfo.objects.filter(date=selected_date) \
        .values_list('city', flat=True) \
        .distinct()
    return cities.count()

# 散点图数据
def get_weather_max_temp(selected_date):
    # 查询数据库
    queryset = WeatherInfo.objects.filter(
        date=selected_date,
        wearther__in=['晴', '阴', '小雨', '多云']
    )
    print("queryset is", queryset)

    # 定义一个字典来存储不同天气状况的 mastHeightDay
    weather_mast_height = {
        '晴': [],
        '阴': [],
        '小雨': [],
        '多云': []
    }

    # 遍历查询结果，将不同天气状况的 mastHeightDay 分别存储到字典中
    for info in queryset:
        weather = info.wearther
        mast_height = info.mastHeightDay

        # 确保 mast_height 不为空
        if mast_height:
            if weather in weather_mast_height:
                weather_mast_height[weather].append(mast_height)

    # 输出分类后的数据
    print("天气状况分类后的 mastHeightDay:", weather_mast_height)

    # 计算晴天和阴天的平均温度
    avg_temperature = {}

    # 处理晴天数据
    if weather_mast_height['晴']:
        # 将字符串转换为整数
        sunny_temps = [int(temp) for temp in weather_mast_height['晴']]
        avg_sunny = sum(sunny_temps) / len(sunny_temps)
        avg_temperature['晴'] = avg_sunny

        # 剔除小于平均温度的数据
        filtered_sunny = [temp for temp in sunny_temps if temp >= avg_sunny]
        # 更新晴天的数据
        weather_mast_height['晴'] = filtered_sunny

    # 处理阴天数据
    if weather_mast_height['阴']:
        cloudy_temps = [int(temp) for temp in weather_mast_height['阴']]
        avg_cloudy = sum(cloudy_temps) / len(cloudy_temps)
        avg_temperature['阴'] = avg_cloudy

        # 剔除小于平均温度的数据
        filtered_cloudy = [temp for temp in cloudy_temps if temp >= avg_cloudy]
        # 更新阴天的数据
        weather_mast_height['阴'] = filtered_cloudy

    # 处理雨天数据
    if weather_mast_height['小雨']:
        rainy_temps = [int(temp) for temp in weather_mast_height['小雨']]
        avg_rainy = sum(rainy_temps) / len(rainy_temps)
        avg_temperature['小雨'] = avg_rainy

        # 剔除小于平均温度的数据
        filtered_rainy = [temp for temp in rainy_temps if temp >= avg_rainy]
        # 更新阴天的数据
        weather_mast_height['小雨'] = filtered_rainy

    # 处理多云数据
    if weather_mast_height['多云']:
        overcast_temps = [int(temp) for temp in weather_mast_height['多云']]
        avg_overcast = sum(overcast_temps) / len(overcast_temps)
        avg_temperature['多云'] = avg_overcast

        # 剔除小于平均温度的数据
        filtered_overcast = [temp for temp in overcast_temps if temp >= avg_overcast]
        # 更新阴天的数据
        weather_mast_height['多云'] = filtered_overcast

    # 输出处理后的数据和平均温度
    print("处理后的天气状况分类后的 mastHeightDay:", weather_mast_height)
    print("平均温度:", avg_temperature)

    # 返回处理后的数据和平均温度
    return weather_mast_height


# 天气状况分布数据
def get_weather_distribution(selected_date):
    # 查询数据库
    queryset = WeatherInfo.objects.filter(
        date=selected_date,
        wearther__in=['晴', '阴', '小雨', '小雪','多云','阴~晴']
    )

    # 定义一个字典来存储每种天气状况的数量
    weather_counts = {
        '晴': 0,
        '阴': 0,
        '小雨': 0,
        '小雪': 0,
        '其他': 0
    }

    # 遍历查询结果，统计每种天气状况的数量
    for info in queryset:
        weather = info.wearther
        if weather in weather_counts:
            weather_counts[weather] +=1
        else:
            weather_counts['其他'] +=1

    total = sum(weather_counts.values())
    if total == 0:
        return {k: 0 for k in weather_counts}  # 防止除以零错误

    # 计算每种天气状况的占比
    weather_percent = {k: round((v / total) * 100) for k, v in weather_counts.items()}
    return weather_percent

def get_wind_distribution(selected_date):
    # 查询数据库
    queryset = WeatherInfo.objects.filter(
        date=selected_date,
        wind__in=['东北风','西北风','东南风','西南风','东风','西风','南风','北风']
    )
    # 定义风向类别
    wind_directions = {
        '东北风': 0,
        '西北风': 0,
        '东南风': 0,
        '西南风': 0,
        '其他': 0
    }
    # 遍历查询结果，统计每种天气状况的数量
    for info in queryset:
        wind = info.wind
        if wind in wind_directions:
            wind_directions[wind] += 1
        else:
            wind_directions['其他'] += 1

    print('wind_direction',wind_directions)

    return wind_directions

# 获取过去30天的温度数据
def get_past_30_days_temp(selected_city, selected_date):
    # 计算过去30天的日期范围
    from datetime import datetime, timedelta
    end_date = datetime.strptime(selected_date, '%Y-%m-%d')
    start_date = end_date - timedelta(days=30)

    # 查询过去30天的温度数据
    data = WeatherInfo.objects.filter(
        city=selected_city,
        date__range=(start_date, end_date)
    ).order_by('date')

    # 准备数据
    dates = []
    temps = []
    mintemps=[]
    for item in data:
        dates.append(item.date.strftime('%Y-%m-%d'))
        temps.append(float(item.mastHeightDay) if item.mastHeightDay else 0.0)
        mintemps.append(float(item.mastSmallDay) if item.mastSmallDay else 0.0)

    return dates, temps,mintemps


#
def getTableData(city):
    weatherListByCity = WeatherInfo.objects.filter(city=city)
    return weatherListByCity

def geteveryDate():
    dateList = WeatherInfo.objects.values_list('date', flat=True).distinct()
    # 将日期对象转换为字符串格式
    formatted_dateList = [date.strftime('%Y-%m-%d') for date in dateList]
    return formatted_dateList
def getWindList():
    weatherList = WeatherInfo.objects.all()
    windList = []
    for i in weatherList:
        windList.append(i.wind)
    windList = list(set(windList))
    # windList = sorted(windList,key=lambda x:get_timestamp(x))
    print(windList)
    return windList

# 城市词云图

def getGlobalData():
    weatherList = WeatherInfo.objects.all()
    addressList = []
    for i in weatherList:
        addressList.append(i.city)
    return list(set(addressList))

